import { truthy, type OptionalFields } from '@gnlab/utils'
import { Steps } from 'antd'
import { ImportantEditModal } from '@/desktop/components'
import Loading from '@/desktop/components/Loading'
import { useQywxsForChoose, type QywxForChooseExtra } from '@/desktop/logics/config-choosing-qywxs'
import services from '@/services'
import {
  getEmptyWelcomeConfig,
  type WelcomeConfig,
  type ConfigQywx,
} from '@/services/features/normal-welcome'
import ChooseQywxs from './choose-qywxs'
import EditConfig from './edit-config'
import './index.module.less'

export type EditingConfig = OptionalFields<WelcomeConfig, 'id'>

export type EditingQywx = ConfigQywx & QywxForChooseExtra

export default function EditConfigModal(props: {
  editing?: null | true | WelcomeConfig
  onFinish: () => void
}) {
  const { editing, onFinish } = props

  const title = truthy(editing) ? (editing === true ? '新建欢迎语' : '编辑欢迎语') : ''

  return <ImportantEditModal title={title} width="800px" open={truthy(editing)} onCancel={onFinish}>
    {truthy(editing) ? <Content editing={editing} onFinish={onFinish} /> : null}
  </ImportantEditModal>
}

enum EditSteps {
  ChooseQywxs = 0,
  Config = 1,
}

function Content(props: { editing: true | WelcomeConfig; onFinish: () => void }) {
  const { editing, onFinish } = props

  const [step, setStep] = useState(EditSteps.ChooseQywxs)
  const [config, setConfig] = useState<EditingConfig>(() =>
    editing === true ? getEmptyWelcomeConfig() : editing,
  )
  const prevStep = useCallback(
    (editedConfig?: Partial<EditingConfig>) => {
      if (editedConfig) setConfig({ ...config, ...editedConfig })
      if (step !== EditSteps.ChooseQywxs) setStep(step - 1)
    },
    [step, config],
  )

  const qywxs = useQywxsForChoose(
    editing === true ? null : editing.id,
    async (configId?: number) => services.features.normalWelcome.getQywxListForConfig(configId),
    qywx => qywx.configId,
  )

  const choosedQywxs = useCallback(
    (wxids: string[]) => {
      setConfig({ ...config, wxids })
      setStep(EditSteps.Config)
    },
    [config],
  )

  return <div styleName="wrap">
    <div styleName="steps-wrap">
      <Steps current={step}>
        <Steps.Step title="选择企微账号" />
        <Steps.Step title="设置欢迎语" />
      </Steps>
    </div>

    {!qywxs ? <Loading /> : null}
    {qywxs && step === EditSteps.ChooseQywxs ? (
      <ChooseQywxs qywxs={qywxs} wxids={config.wxids} choosed={choosedQywxs} />
    ) : null}
    {qywxs && step === EditSteps.Config ? (
      <EditConfig config={config} goPrev={prevStep} onFinish={onFinish} />
    ) : null}
  </div>
}
